<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2019/6/25
 * Time: 18:27
 */

namespace app\common\service\weekAttention;

use app\common\service\CommonService;
use think\Db;
use app\common\service\lastWeek\LastWeekControlAnalysisService;
use think\facade\Config;


class WeekAttentionControlTraceService
{
    /**
     * 减排前、减排后、实测值
     * @author yy by 2019/7/1
     * @param array $param
     * @return array
     */
    public function getReduceForecast($param = [])
    {
        $pollutant_name = str_replace('.', '', strtolower($param['pollutant_name']));
        # 获取减排前预报
        # 判断周几
        $week = date('w');
        if ($week == 1) {
            $reduceForecastData = Db::query("select $pollutant_name, DATE_FORMAT(predict_time, '%Y-%m-%d') as date
                               from air_quality_station_aqi_forecast_day
                               where region_id = ? and station_id = ? and is_integer = 1 and DATE_FORMAT(publish_time, '%Y-%m-%d') = ? and DATE_FORMAT(predict_time, '%Y-%m-%d') between ? and ?",
                [$param['region_id'], $param['station_id'], $param['start_time'], $param['start_time'], $param['end_time']]);
        } else {
            $yesterday          = date('Y-m-d', strtotime("-1 day"));
            $now                = date('Y-m-d', time());
            $before_data        = Db::query("select $pollutant_name, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                               from air_quality_station_aqi_forecast_day
                               where region_id = ? and station_id = ? and is_integer = 1 and publish_time = predict_time and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
                [$param['region_id'], $param['station_id'], $param['start_time'], $yesterday]);
            $predict_data       = Db::query("select $pollutant_name, DATE_FORMAT(predict_time, '%Y-%m-%d') as date
                               from air_quality_station_aqi_forecast_day
                               where region_id = ? and station_id = ? and is_integer = 1 and DATE_FORMAT(publish_time, '%Y-%m-%d') = ? and DATE_FORMAT(predict_time, '%Y-%m-%d') between ? and ?",
                [$param['region_id'], $param['station_id'], $now, $now, $param['end_time']]);
            $reduceForecastData = array_merge($before_data, $predict_data);
        }
        #实测值
        $realData = Db::query("select $pollutant_name, DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                                    from air_quality_station_aqi_realtime_day
                                    where region_id = ? and station_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?",
            [$param['region_id'], $param['station_id'], $param['start_time'], $param['end_time']]);
        # 空数据处理
        $lastWeekControlAnalysisService = new LastWeekControlAnalysisService();
        $reduceForecastData             = $lastWeekControlAnalysisService->getAllData($param, $reduceForecastData, $pollutant_name);
        $realData                       = $lastWeekControlAnalysisService->getAllData($param, $realData, $pollutant_name);

        # 减排后预报  TODO 涉及到预案里面的减排日期
        $reduceLateData = [];
        for ($i = 0; $i < count($reduceForecastData['date']); $i++) {
            $reduceLateData['date'][$i]    = $reduceForecastData['date'][$i];
            $reduceLateData['data'][0][$i] = '-';
        }
        $result = [
            'reduceForecastData' => $reduceForecastData,
            'reduceLateData'     => $reduceLateData,
            'realData'           => $realData,
        ];
        return $result;
    }

    /**
     * 平均运行浓度和效率
     * @author yy by 2019/6/25
     * @param array $param
     * @return mixed
     */
    public function getConcentrationEfficiency($param = [])
    {
        # 脱硫表或脱硝表 晋能热电
        $table = $param['is_sulfur'] ? 'company_industry_monitor_sulfur_day' : 'company_industry_monitor_nitre_day';
        $data  = Db::query("select avg(operation_concentration) as operation_concentration, avg(operating_efficiency) as operating_efficiency, company_name,DATE_FORMAT(publish_time, '%Y-%m-%d') as date
                            from $table
                            where power = 1 and company_id = ? and DATE_FORMAT(publish_time, '%Y-%m-%d') between ? and ?
                            group by publish_time", [$param['company_id'], $param['start_time'], $param['end_time']]);
        # 日期补全
        $lastWeekControlAnalysisService = new LastWeekControlAnalysisService();
        $operation_concentration_data   = $lastWeekControlAnalysisService->getAllData($param, $data, 'operation_concentration');
        $operating_efficiency_data      = $lastWeekControlAnalysisService->getAllData($param, $data, 'operating_efficiency');
        return ['concentration' => $operation_concentration_data, 'efficiency' => $operating_efficiency_data];
    }

    /**
     * 管控企业运行趋势（减排前 减排后）
     * @author yy by 2019/6/26
     * @param array $param
     * @return array
     * @throws \MongoDB\Driver\Exception\Exception
     */
    public function getCompanyOperationTrend($param = [])
    {
        $commonService   = new CommonService();
        $mongodb_huanxin = new \MongoDB\Driver\Manager(Config::get('mongodb_url'));
        $new_time        = $commonService->getMongoTime($param, 0);
        # 脱硫表或脱硝表 晋能热电 只有实测数据
        $table    = $param['is_sulfur'] == 1 ? 'company_industry_monitor_sulfur_minute' : 'company_industry_monitor_nitre_minute';
        $emission = $param['is_sulfur'] == 1 ? 'emissions' : 'emission';
        # 减排前
        $document           = [
            'aggregate'    => $table,
            'pipeline'     => [
                [
                    '$project' => [
                        'publish_time' => 1,
                        'company_id'   => 1,
                        $emission      => 1,
                        'time'         => ['$substr' => ['$publish_time', 0, 10]],
                    ],
                ],
                [
                    '$match' => [
                        'company_id'   => (int)$param['company_id'],
                        'publish_time' => [
                            '$gte' => $new_time['start_time'],
                            '$lte' => $new_time['end_time'],
                        ],
                    ]
                ],
                [
                    '$group' => [
                        '_id'             => '$time',
                        'emissions_total' => ['$sum' => '$' . $emission],
                    ]
                ],
                [
                    '$sort' => [
                        "_id" => 1,
                    ]
                ]
            ],
            'allowDiskUse' => true,
        ];
        $command            = new \MongoDB\Driver\Command($document);
        $rows               = $mongodb_huanxin->executeCommand('huanxin', $command)->toArray();
        $contribution_trend = json_decode(json_encode($rows, 320), true);
        $num                = count($contribution_trend[0]['result']);
        $before_data        = [];
        if ($num > 0) {
            foreach ($contribution_trend[0]['result'] as $k => $v) {
                $before_data[$k]['date']            = $v['_id'];
                $before_data[$k]['emissions_total'] = $v['emissions_total'];
            }
        }
        # 日期补全
        $lastWeekControlAnalysisService = new LastWeekControlAnalysisService();
        $before_data                    = $lastWeekControlAnalysisService->getAllData($param, $before_data, 'emissions_total');
        $before_data['data'][0]         = $commonService->getRealData($before_data['data'][0]);
        # 方案值 TODO
        $before_control = [];
        $after_data     = [];
        $after_control  = [];
        for ($i = 0; $i < count($before_data['date']); $i++) {
            $before_control['date'][$i]    = $before_data['date'][$i];
            $before_control['data'][0][$i] = '-'; //方案值
            # 减排后 = 减排前 - 方案值; TODO 减排日期确定下？
            $after_data['date'][$i]       = $before_data['date'][$i];
            $after_data['data'][0][$i]    = '-';
            $after_control['date'][$i]    = $before_data['date'][$i];
            $after_control['data'][0][$i] = '-'; //方案值
        }
        $result = [
            'before' => [
                'date' => $before_data['date'],
                'data' => [$before_control['data'][0], $before_data['data'][0]]
            ],
            'after'  => [
                'date' => $after_data['date'],
                'data' => [$after_control['data'][0], $after_data['data'][0]]
            ],

        ];
        return $result;
    }
}